package cn.ivicar.oss.quartz;

import cn.com.carsmart.ws.ibatis.model.BaseExample;
import cn.com.carsmart.ws.model.ActivateStat;
import cn.com.carsmart.ws.model.Vehicle;
import cn.com.carsmart.ws.service.ActivateStatManager;
import cn.com.carsmart.ws.service.VehicleManager;
import cn.ivicar.oss.guice.OssGuiceConfig;
import org.quartz.Job;
import org.quartz.JobExecutionContext;
import org.quartz.JobExecutionException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.List;

/**
 *统计每日新增设备数
 */
public class IncreaseStatisticJob implements Job {
    private static transient final Logger LOGGER = LoggerFactory.getLogger(IncreaseStatisticJob.class);

    private static VehicleManager vehicleManager = OssGuiceConfig.getStaticInjector().getInstance(VehicleManager.class);
    private static ActivateStatManager activateStatManager = OssGuiceConfig.getStaticInjector()
            .getInstance(ActivateStatManager.class);

    @Override
    public void execute(JobExecutionContext context) throws JobExecutionException {

        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");

        LOGGER.info(String.format("定时任务：IncreaseStatisticJob开始执行，开始时间 = %s",sdf.format(new Date())));

        Calendar c = Calendar.getInstance();
        c.setTime(new Date());
        c.add(Calendar.DATE, -1);
        c.set(Calendar.HOUR_OF_DAY, 0);
        c.set(Calendar.MINUTE, 0);
        c.set(Calendar.SECOND, 0);
        c.set(Calendar.MILLISECOND, 0);
        Date start = c.getTime();

        c.set(Calendar.HOUR_OF_DAY, 23);
        c.set(Calendar.MINUTE, 59);
        c.set(Calendar.SECOND, 59);
        c.set(Calendar.MILLISECOND, 999);
        Date end = c.getTime();

        BaseExample example = this.vehicleManager.getExample();
        example.or().andIdBetween(start, end, "created");
        int count = this.vehicleManager.countByExample(example);

        List<Vehicle> all = this.vehicleManager.list();

        ActivateStat activateStat = new ActivateStat();
        activateStat.setActivateCount(count);
        activateStat.setTotalCount(all.size());
        activateStat.setStatTime(start);
        SimpleDateFormat sdfd = new SimpleDateFormat("yyyy-MM-dd");
        String statDate = sdfd.format(start);
        LOGGER.info(String.format("每日新增设备统计完成：日期：%s, 新增数量： %s", statDate, count));

        this.activateStatManager.insert(activateStat);

        LOGGER.info(String.format("定时任务：IncreaseStatisticJob执行完毕，结束时间 = %s",sdf.format(new Date())));
    }
}
